<?php namespace App\Models\Power;

use App\Models\Base\PowerBase;
use App\Models\Power\Gun;
use App\Models\Power\Price;
use App\Models\Power\Stop;

class Pile extends PowerBase
{

    protected $table = 'cdz_electric_pile';

    protected $fillable = [];

    protected $dates = [];

    public static $rules = [
        // Validation rules
    ];

    /**
     * 首页获取电桩信息
     * params Array condition
     */
    public function getPile($params = [''])
    {

        $gun = new Gun();
        $range = getPositionRange($params['lng'], $params['lat']);
        $redis_info = $this->redis->hgetall('CDZCHARGEORDERPILENO');
        $query = self::query();
        $query->whereBetween('lng', [$range['minLng'], $range['maxLng']]);
        $query->whereBetween('lat', [$range['minLat'], $range['maxLat']]);
        $query->whereStatus(1);

        if (isset($params['condition'])) {
            $condition = json_decode($params['condition'], true);
        }
        // dd($condition);

        // if (isset($condition['type'])) {
        //     if (strstr($condition['type'], ',')) {
        //         $type = explode(',', $condition['type']);
        //     } else {
        //         $type = [intval($condition['type'])];
        //     }
        // }
        // if (isset($condition['standard'])) {
        //     if (strstr($condition['standard'], ',')) {
        //         $standard = explode(',', $condition['standard']);
        //     } else {
        //         $standard = [$condition['standard']];
        //     }
        // }

        // if (isset($condition['p_money'])) {
        //     if (strstr($condition['p_money'], ',')) {
        //         $pmoney = explode(',', $condition['p_money']);
        //     } else {
        //         $pmoney = [$condition['p_money']];
        //     }
        // }

        if(isset($condition)) {

            foreach($condition as $key => $value) {

                if (isset($condition[$key]['type'])) {
                    if (strstr($condition[$key]['type'], ',')) {
                        $type = explode(',', $condition[$key]['type']);
                    } else {
                        $type = [intval($condition[$key]['type'])];
                    }
                }
                if (isset($condition[$key]['standard'])) {
                    if (strstr($condition[$key]['standard'], ',')) {
                        $standard = explode(',', $condition[$key]['standard']);
                    } else {
                        $standard = [$condition[$key]['standard']];
                    }
                }
        
                if (isset($condition[$key]['p_money'])) {
                    if (strstr($condition[$key]['p_money'], ',')) {
                        $pmoney = explode(',', $condition[$key]['p_money']);
                    } else {
                        $pmoney = [$condition[$key]['p_money']];
                    }
                }

                if (isset($condition[$key]['using'])) {
                    $using = $condition[$key]['using'];
                }

            }

        }

        isset($type) && $query->whereType($type);
        isset($standard) && $query->whereStandard($standard);
        isset($pmoney) && $query->wherePmoney($pmoney);
        $data = $query->limit(10)->get()->toArray();
        // dd($query -> toSql());
        foreach ($data as $key => $value) {
            $check_gun = $gun->getPileUsing($value['no'], $value['id']);
            $data[$key]['using'] = 0;
            $data[$key]['using'] = $check_gun['is_using'];
            $data[$key]['count_gun'] = 0;
            $data[$key]['count_not_using'] = 0;
            $data[$key]['count_gun'] = $check_gun['count_gun'];
            $data[$key]['count_not_using'] = $check_gun['count_not_using'];
            if (isset($using) && $data[$key]['using'] == 1) {
                unset($data[$key]);
            }
        }

        return $data;

    }

    /**
     * 电桩详情
     * params Array condition
     */
    public function getPileByNo($condition = [])
    {

        $gun = new Gun();
        $price = new Price();

        if(strpos($condition['no'], '-')) {
            $temp = explode('-', $condition['no']);
            $no = $temp[0];
            $current_gun = $temp[1];
        } else {
            $no = $condition['no'];
        }

        $query = self::query();
        $query-> whereNo($no);
        $query-> whereStatus(1);
        $data = $query -> first();
        
        if($data) {

            if($data -> stop) {
                $data -> stop_name = $data -> stop -> name;
                unset($data -> stop);
            } else {
                $data -> stop_name = null;
            }
            $check_gun = $gun->getPileUsing($data['no'], $data['id']);
            if(isset($current_gun)) {
                $data['current_gun'] = $current_gun;
            } else {
                $data['current_gun'] = null;
            }
            $data['using'] = 0;
            $data['using'] = $check_gun['is_using'];
            $data['during'] = $price->getPilePrice($data['no'], $data['id']);
            
        }

        return $data;

    }

    /**
     * 根据关键字获取电桩
     * params String params
     */
    public static function findByKeyword($params = '', $range)
    {

        $result = ['data' => [], 'range' => []];
        $query = self::query();
        // $query->whereNoLike($params['keyword']);
        $query->whereLike($params);
        $range && $query->whereStopNotIn($range);
        $query->whereStatus(1);
        $data = $query->get()->toArray();
        // dd($range);
        // dd($query -> toSql());
        if ($data) {
            foreach ($data as $key => $value) {
                if ($value['stop_id']) {
                    $data[$key]['stop_name'] = '';
                    $data[$key]['stop_name'] = self::find($value['id'])->stop->name;
                }
                $gun = new Gun();
                $check_gun = $gun->getPileUsing($value['no'], $value['id']);
                $data[$key]['using'] = 0;
                $data[$key]['using'] = $check_gun['is_using'];
                $data[$key]['count_gun'] = 0;
                $data[$key]['count_not_using'] = 0;
                $data[$key]['count_gun'] = $check_gun['count_gun'];
                $data[$key]['count_not_using'] = $check_gun['count_not_using'];
            }
        }
        return $data;

    }

    /**
     * redis订单获取电桩电站详情
     * params Array $order
     */
    public function getPileByOrder($order)
    {

        $query = self::query();
        $query-> whereNo($order['pile_no']);
        $pile = $query -> first();
        $order['stop_name'] = '';
        
        if($pile) {

            $price = $pile -> price -> toArray();
            $this_price = getOrderPrice($order['begin'], $price);
            $order['electric_fee'] = $this_price['ele'];
            $order['service_fee'] = $this_price['service'];
            //如果存在电站
            if($pile -> stop) {
                $name = $pile -> stop -> name;
                $order['stop_name'] = $name;
                if($name) {
                    $order['stop_name'] = $name;
                } else {
                    $order['stop_name'] = '未知';
                }
            }
            
        } else {

            $order['pile_no'] = $order['pile_no'] . '（该电桩编号已更改或该电桩已下线）';
            $order['electric_fee'] = '未知';
            $order['service_fee'] = '未知';

        }

        return $order;

    }

    public function scopeWhereType($query, $type)
    {
        return $query->whereIn('type', $type);
    }

    public function scopeWhereStandard($query, $standard)
    {
        return $query->whereIn('standard', $standard);
    }

    public function scopeWherePmoney($query, $pmoney)
    {
        return $query->whereIn('p_money', $pmoney);
    }

    public function scopeWhereNo($query, $no)
    {
        return $query->where('no', '=', $no);
    }

    public function scopeWhereLike($query, $keyword)
    {
        return $query->where('address', 'like', '%' . $keyword . '%')->orWhere('no', 'like', '%' . $keyword . '%');
    }

    public function scopeWhereStopNotIn($query, $range)
    {
        return $query->whereNotIn('stop_id', $range)->orWhere('stop_id', '=', null);
    }

    /**
     * 和Stop模型的多对一关联
     */
    public function stop()
    {
        return $this->belongsTo('App\Models\Power\Stop', 'stop_id');
    }

    /**
     * 和Price模型的一对多关联
     */
    public function price()
    {
        return $this->hasMany('App\Models\Power\Price', 'pile_id');
    }

    /**
     * 和Operate模型的一对一关联
     */
    public function operate()
    {
        return $this->hasOne('App\Models\Power\Operate', 'id', 'depl_id');
    }

    // public static function test() {
    //     $pile = self::find(1);
    //     $test = $pile -> stop->id;
    //     // dd($test);
    //     return $test;
    // }
}
